/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.feed_records.modular.feedusagerecords.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.biz.modular.feedtype.entity.BizFeedType;
import vip.xiaonuo.biz.modular.feedtype.mapper.BizFeedTypeMapper;
import vip.xiaonuo.column.modular.column.entity.BizColumn;
import vip.xiaonuo.column.modular.column.mapper.BizColumnMapper;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.feed.modular.feedstocks.entity.BizFeedStocks;
import vip.xiaonuo.feed.modular.feedstocks.mapper.BizFeedStocksMapper;
import vip.xiaonuo.feed_records.modular.feedusagerecords.entity.BizFeedUsageRecords;
import vip.xiaonuo.feed_records.modular.feedusagerecords.entity.FeedUsageRecordsView;
import vip.xiaonuo.feed_records.modular.feedusagerecords.mapper.BizFeedUsageRecordsMapper;
import vip.xiaonuo.feed_records.modular.feedusagerecords.mapper.FeedUsageRecordsViewMapper;
import vip.xiaonuo.feed_records.modular.feedusagerecords.param.BizFeedUsageRecordsAddParam;
import vip.xiaonuo.feed_records.modular.feedusagerecords.param.BizFeedUsageRecordsEditParam;
import vip.xiaonuo.feed_records.modular.feedusagerecords.param.BizFeedUsageRecordsIdParam;
import vip.xiaonuo.feed_records.modular.feedusagerecords.param.BizFeedUsageRecordsPageParam;
import vip.xiaonuo.feed_records.modular.feedusagerecords.service.BizFeedUsageRecordsService;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * 饲料使用记录Service接口实现类
 *
 * @author zyb
 * @date  2023/12/14 17:11
 **/
@Service
public class BizFeedUsageRecordsServiceImpl extends ServiceImpl<BizFeedUsageRecordsMapper, BizFeedUsageRecords> implements BizFeedUsageRecordsService {

    @Resource
    private BizFeedTypeMapper feedTypeMapper;

    @Resource
    private BizColumnMapper columnMapper;

    @Resource
    private BizFeedStocksMapper feedStocksMapper;

    @Resource
    private FeedUsageRecordsViewMapper feedUsageRecordsViewMapper;

    @Override
    public Page<FeedUsageRecordsView> page(BizFeedUsageRecordsPageParam bizFeedUsageRecordsPageParam) {
        QueryWrapper<FeedUsageRecordsView> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isNotEmpty(bizFeedUsageRecordsPageParam.getFeedName())) {
            queryWrapper.lambda().like(FeedUsageRecordsView::getTypeName, bizFeedUsageRecordsPageParam.getFeedName());
        }
        if(ObjectUtil.isNotEmpty(bizFeedUsageRecordsPageParam.getColumnName())) {
            queryWrapper.lambda().like(FeedUsageRecordsView::getColumnName, bizFeedUsageRecordsPageParam.getColumnName());
        }
        if(ObjectUtil.isNotEmpty(bizFeedUsageRecordsPageParam.getStartInputDate()) && ObjectUtil.isNotEmpty(bizFeedUsageRecordsPageParam.getEndInputDate())) {
            queryWrapper.lambda().between(FeedUsageRecordsView::getInputDate, bizFeedUsageRecordsPageParam.getStartInputDate(), bizFeedUsageRecordsPageParam.getEndInputDate());
        }
        if(ObjectUtil.isAllNotEmpty(bizFeedUsageRecordsPageParam.getSortField(), bizFeedUsageRecordsPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(bizFeedUsageRecordsPageParam.getSortOrder());
            queryWrapper.orderBy(true, bizFeedUsageRecordsPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(bizFeedUsageRecordsPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(FeedUsageRecordsView::getId);
        }
        return feedUsageRecordsViewMapper.selectPage(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(BizFeedUsageRecordsAddParam bizFeedUsageRecordsAddParam) {
        BizFeedUsageRecords bizFeedUsageRecords = BeanUtil.toBean(bizFeedUsageRecordsAddParam, BizFeedUsageRecords.class);
        Integer typeId = bizFeedUsageRecordsAddParam.getTypeId();
        String columnId = bizFeedUsageRecordsAddParam.getColumnId();
        LambdaQueryWrapper<BizFeedType> typeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<BizColumn> columnLambdaQueryWrapper = new LambdaQueryWrapper<>();

        typeLambdaQueryWrapper.select(BizFeedType::getName).eq(BizFeedType::getId, typeId);
        columnLambdaQueryWrapper.select(BizColumn::getName).eq(BizColumn::getId, columnId);

        BizFeedType bizFeedType = feedTypeMapper.selectOne(typeLambdaQueryWrapper);
        BizColumn bizColumn = columnMapper.selectOne(columnLambdaQueryWrapper);

        if (bizFeedType == null){
            throw new CommonException("未找到该类型饲料");
        }

        if (bizColumn == null){
            throw new CommonException("未找到该栏区");
        }

        checkStock(bizFeedUsageRecordsAddParam);
        this.save(bizFeedUsageRecords);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BizFeedUsageRecordsEditParam bizFeedUsageRecordsEditParam) {
        BizFeedUsageRecords bizFeedUsageRecords = this.queryEntity(bizFeedUsageRecordsEditParam.getId());
        BeanUtil.copyProperties(bizFeedUsageRecordsEditParam, bizFeedUsageRecords);
        this.updateById(bizFeedUsageRecords);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<BizFeedUsageRecordsIdParam> bizFeedUsageRecordsIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(bizFeedUsageRecordsIdParamList, BizFeedUsageRecordsIdParam::getId));
    }

    @Override
    public BizFeedUsageRecords detail(BizFeedUsageRecordsIdParam bizFeedUsageRecordsIdParam) {
        return this.queryEntity(bizFeedUsageRecordsIdParam.getId());
    }

    @Override
    public BizFeedUsageRecords queryEntity(Integer id) {
        BizFeedUsageRecords bizFeedUsageRecords = this.getById(id);
        if(ObjectUtil.isEmpty(bizFeedUsageRecords)) {
            throw new CommonException("饲料使用记录不存在，id值为：{}", id);
        }
        return bizFeedUsageRecords;
    }

    private void checkStock(BizFeedUsageRecordsAddParam bizFeedUsageRecordsAddParam){
        LambdaQueryWrapper<BizFeedStocks> feedStocksLambdaQueryWrapper = new LambdaQueryWrapper<>();
        Integer feedId = bizFeedUsageRecordsAddParam.getTypeId();
        // 检查库存是否存在
        feedStocksLambdaQueryWrapper.select(BizFeedStocks::getQuantity).eq(BizFeedStocks::getTypeId, feedId);
        BizFeedStocks bizFeedStocks = feedStocksMapper.selectOne(feedStocksLambdaQueryWrapper);
        if (null == bizFeedStocks){
            throw new CommonException("该类型饲料暂无库存，请重新选择！");
        }
        // 比较库存与使用量
        BigDecimal quantity = bizFeedStocks.getQuantity();
        BigDecimal inputQuantity = bizFeedUsageRecordsAddParam.getInputQuantity();
        // 这里的两个BigDecimal精度相同，可以直接比较
        if (quantity.subtract(inputQuantity).compareTo(BigDecimal.ZERO) < 0){
            throw new CommonException("库存不足，请重新输入！");
        }
    }
}
